import javax.swing.tree.TreeNode;
import java.util.LinkedList;
import java.util.Queue;

public class dfsandbfs {
    static class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;
        int deep;

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public static void main(String[] args) {
        TreeNode node7 = new TreeNode(7,null,null);
        TreeNode node6 = new TreeNode(6,node7,null);
        TreeNode node5 = new TreeNode(5,null,null);
        TreeNode node4 = new TreeNode(4,null,null);
        TreeNode node3 = new TreeNode(3,node6,null);
        TreeNode node2 = new TreeNode(2,node4,node5);
        TreeNode node1 = new TreeNode(1,node2,node3);

        System.out.println(minDepth(node1));
        System.out.println(minDepth2(node1));
    }
//bfs
    private static int minDepth2(TreeNode head) {
        Queue<TreeNode> queue = new LinkedList();
        if(head==null){
            return 0;
        }
        head.deep=1;
        queue.offer(head);
        while (!queue.isEmpty()){
            TreeNode node = queue.poll();
            if(node.left==null&&node.right==null){
                return node.deep;
            }
            if(node.left!=null){
                node.left.deep = node.deep+1;
                queue.offer(node.left);
            }
            if(node.right!=null){
                node.right.deep = node.deep+1;
                queue.offer(node.right);
            }
        }


        return 0;
    }
//dfs
    private static int minDepth(TreeNode head) {
        if(head==null){
            return 0;
        }
        if (head.left==null&&head.right==null){
            return 1;
        }
        int min = Integer.MAX_VALUE;
        if(head.left!=null){
            min = Math.min(min,minDepth(head.left));
        }
        if(head.right!=null){
            min = Math.min(min,minDepth(head.right));
        }

        return min+1;
    }
}
